var express = require('express');
var router = express.Router();
var fs = require('fs');
var docdb = global.config.docdb;
var docspath = global.config.docspath;

// new doc
router.get('/new', function (req, res) {
    res.render('docs_edit', {
        doc: {
            title: '新建文档',
            content: fs.readFileSync(docspath + 'temp/docs.md', 'utf-8')
        }
    })
});

// create doc
router.post('/', function (req, res) {
    var now = new Date();
    docdb.insert({
        title: req.body.title,
        content: req.body.content,
        create_time: now,
        update_time: now
    }, function (err, newdoc) {
        res.redirect('/')
    });
});

// edit doc
router.get('/:id/edit', function (req, res) {
    docdb.find({_id: req.params.id}, function (err, docs) {
        res.render('docs_edit', {
            doc: docs[0]
        })
    })
});

// update doc
router.post('/:id', function (req, res) {
    docdb.update({_id: req.params.id}, {
        title: req.body.title,
        content: req.body.content,
        update_time: new Date()
    }, {}, function (err, numReplaced) {
        res.redirect('/')
    });
});

// delete
router.delete('/:id', function (req, res) {
    docdb.remove({_id: req.params.id}, {}, function (err, numRemoved) {

        console.log(arguments);
        
        res.status(200).send('ok');
    });
});

// view doc
router.get('/:id', function (req, res) {
    docdb.find({_id: req.params.id}, function (err, docs) {
        res.render('docs_view', {
            doc: docs[0]
        })
    })
});

module.exports = router;
